package com.ly.lypopupwindowdemo.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.ly.lypopupwindowdemo.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class SDCardActivity extends AppCompatActivity {

    private Button write,read;
    private ImageView iv;
    private String filename;

    /**
     * http://blog.csdn.net/android_hasen/article/details/9353503
     *
     * http://blog.csdn.net/yongh701/article/details/46669189
     * @param savedInstanceState
     */


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sdcard);

        write = (Button) findViewById(R.id.write);
        read = (Button) findViewById(R.id.read);
        iv = (ImageView) findViewById(R.id.iv);

        File sdcard = Environment.getExternalStorageDirectory();
        filename = sdcard + "/ly.jpg";

        write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //写入
                saveImg();
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readImg();
            }
        });

    }

    private static final String TAG = "SDCardActivity";


    private void readImg() {

        boolean isSdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sdcard是否存在
        if (isSdCardExist){
            File file = new File(filename);
            Log.e(TAG, "readImg: sdcard路径==="+file.toString() );
            if (file.exists()){
                Bitmap bitmap = BitmapFactory.decodeFile(filename);
                iv.setImageBitmap(bitmap);
            }
        } else {
            Toast.makeText(this, "sd卡不存在", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveImg() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg) ;
        File file = new File(filename) ;
        if(!file.exists()){
            try {
                file.createNewFile() ;
                FileOutputStream fos = new FileOutputStream(file) ;
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, fos) ;
                Toast.makeText(this, "save success", Toast.LENGTH_SHORT).show();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
